package kd.bos.openapi.demo.sample.custom.service.impl;

import com.alibaba.fastjson.JSON;
import kd.bos.openapi.demo.sample.custom.dto.CustomApiResult;
import kd.bos.openapi.demo.sample.custom.dto.CustomOrderDto;
import kd.bos.openapi.demo.sample.custom.service.CustomOrderService;
import kd.bos.openapi.sdk.dto.OrderDto;
import kd.bos.openapi.sdk.exception.APIException;
import kd.bos.openapi.sdk.request.RequestQueryDto;
import kd.bos.openapi.sdk.response.result.ResultCode;
import kd.bos.openapi.sdk.util.OpenApiUtil;
import kd.bos.openapi.sdk.util.PropertyUtil;
import kd.bos.openapi.sdk.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Deacription 自定义API服务订单服务接口
 * @author johnz
 * @date 2022年4月6日
 */
@Slf4j
public class CustomOrderServiceImpl implements CustomOrderService {
    @Override
    public CustomApiResult findOrders(RequestQueryDto<OrderDto> query) throws APIException {
        log.info("request.data:{}", JSON.toJSONString(query));
        if (query == null) {
            // 异常
            return new CustomApiResult(ResultCode.BUSINESS_PARAM_NULL_EXCEPTION);
        }
        // 构建请求参数
        CustomOrderDto customOrderDto = new CustomOrderDto();
        customOrderDto.setBillNo(query.getData().getBillno());
        customOrderDto.setPageSize(query.getPageSize());
        customOrderDto.setPageNo(query.getPageNo());
        Map<String,Object> params = new HashMap<>();
        params.put("queryDto", customOrderDto);
        // 请求URL
        String sortUrl = PropertyUtil.getProperty("bos.order.customFindOrders");
        // 处理结果
        String res = OpenApiUtil.doPostByJson(sortUrl, params);
        // 构建请求响应对象，根据返回的errorCode做不同的业务处理
        // 具体的errorCode,可以参考 kd.bos.openapi.common.constant.ApiErrorCode
        CustomApiResult<List<CustomOrderDto>> responseDto = new CustomApiResult();
        if (!StringUtils.isEmpty(res)) {
            responseDto = JSON.parseObject(res, CustomApiResult.class);
        }
        // 此处根据其他模块调用的需要封装结果，现在以返回Controller为例
        return responseDto;
    }

    @Override
    public String getFindOrdersWsdl() throws APIException {
        Map<String, Object> params = new HashMap<>();
        params.put("wsdl", "wsdl");
        String wsdl = OpenApiUtil.doGet(PropertyUtil.getProperty("bos.order.customFindOrders"), params);
        log.info("wsdl:{}",wsdl);
        return wsdl;
    }

    @Override
    public String findOrdersWebService(String requestXml) throws APIException {
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "text/xml;charset=UTF-8");
        log.info("webservice request:{}", requestXml);
        String result = OpenApiUtil.doPostByXml(PropertyUtil.getProperty("bos.order.customFindOrders"), header, requestXml);
        log.info("webservice result:{}", result);
        return result;
    }

}
